package com.cvte.boe.media.views.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageButton;

import com.cvte.boe.media.R;

import java.lang.ref.WeakReference;

/**
 * Created by wuguitong on 2018/5/25.
 */
public class LongClickImageButton extends ImageButton{
    private Handler longClickHandr;
    private long intervalTime = 200;
    private boolean isRepeatClick = false;
    private static final int MSG_LONG_CLICK = 0;
    public LongClickImageButton(Context context) {
        super(context);
    }

    public LongClickImageButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }

    public LongClickImageButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context,attrs);
    }
    private void init(Context context,AttributeSet attrs){
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.LongClickImageButton);
        if(typedArray != null){
            isRepeatClick = typedArray.getBoolean(R.styleable.LongClickImageButton_isRepeatClick,false);
            if(isRepeatClick) {
                longClickHandr = new LongClickHander(this);
                setOnLongClickListener(new OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {
                        new Thread(new LongClickThread()).start();
                        return true;
                    }
                });
            }
        }
    }
    private class LongClickThread implements Runnable{
        int num;
        @Override
        public void run() {
            while (LongClickImageButton.this.isPressed()){
                num++;
                if(num % 5 == 0){
                    longClickHandr.sendEmptyMessage(MSG_LONG_CLICK);
                }
                SystemClock.sleep(intervalTime/5);
            }
        }
    }
    private static class LongClickHander extends Handler{
        private WeakReference<LongClickImageButton> ref;
        LongClickHander(LongClickImageButton btn){
            ref = new WeakReference<LongClickImageButton>(btn);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LONG_CLICK:
                    LongClickImageButton btn = ref.get();
                    if (btn != null) {
                        btn.performClick();
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
